const db = require('../models');
const { Op, Sequelize } = require('sequelize');
const moment = require('moment');

/**
 * 获取销售活跃度报告数据
 */
exports.getActivityReport = async (req, res) => {
  try {
    const { startDate, endDate, userIds } = req.query;
    
    // 设置默认日期范围为过去7天
    const start = startDate ? moment(startDate).startOf('day') : moment().subtract(7, 'days').startOf('day');
    const end = endDate ? moment(endDate).endOf('day') : moment().endOf('day');
    
    // 日期合法性检查
    if (!start.isValid() || !end.isValid()) {
      return res.status(400).json({ 
        message: '无效的日期格式',
        details: { startDate, endDate }
      });
    }
    
    // 确保结束日期不超过当前日期
    const currentDate = moment().endOf('day');
    const validEnd = end.isAfter(currentDate) ? currentDate : end;
    
    // 过滤用户ID - 添加更多错误处理
    let userIdFilter = {};
    if (userIds) {
      try {
        // 移除任何可能存在的冒号
        let cleanUserIds = userIds.replace(/:/g, '');
        
        const parsedIds = cleanUserIds.split(',')
          .map(id => id.trim())
          .filter(id => id && !isNaN(parseInt(id)))
          .map(id => parseInt(id));
          
        if (parsedIds.length > 0) {
          userIdFilter = { id: { [Op.in]: parsedIds } };
        }
        
        console.log('解析后的用户ID:', parsedIds);
      } catch (parseError) {
        console.error('解析用户ID失败:', parseError, userIds);
        // 使用空过滤器，不筛选用户
      }
    }
    
    // 记录请求参数
    console.log('活动报告查询参数:', {
      startDate: start.format('YYYY-MM-DD'),
      endDate: validEnd.format('YYYY-MM-DD'),
      userIdFilter
    });
    
    // 查询条件：日期范围
    const dateRangeFilter = {
      createdAt: {
        [Op.between]: [start.toDate(), validEnd.toDate()]
      }
    };
    
    // 用户活跃度数据
    const users = await db.User.findAll({
      where: {
        ...userIdFilter,
        role: 'sales'
      },
      attributes: ['id', 'username', 'fullName']
    });
    
    // 记录查询到的用户
    console.log(`查询到${users.length}个销售用户`);
    
    // 安全防护 - 检查模型是否存在
    if (!db.Message) {
      console.error('Message模型未定义');
      return res.status(500).json({
        message: '服务器配置错误: Message模型未定义',
        error: 'MODEL_NOT_DEFINED'
      });
    }
    
    // 汇总数据 - 添加错误处理
    try {
      let messageStats = [];
      let totalMessages = [];
      
      try {
        // 消息类型统计
        messageStats = await db.Message.findAll({
          where: dateRangeFilter,
          attributes: [
            'type',
            [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
          ],
          group: ['type']
        });
      } catch (msgStatsError) {
        console.error('获取消息类型统计失败:', msgStatsError);
        messageStats = []; // 使用空数组
      }
      
      try {
        // 总消息数
        totalMessages = await db.Message.findAll({
          where: dateRangeFilter,
          attributes: [
            'fromMe',
            [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
          ],
          group: ['fromMe']
        });
      } catch (totalMsgError) {
        console.error('获取总消息数统计失败:', totalMsgError);
        totalMessages = []; // 使用空数组
      }
      
      // 处理总消息数据
      const sentMessages = totalMessages.find(m => m.fromMe) || { count: 0 };
      const receivedMessages = totalMessages.find(m => !m.fromMe) || { count: 0 };
      
      // 每日统计数据 - 带错误处理
      let dailyStats = [];
      try {
        dailyStats = await getDailyStats(start, validEnd);
      } catch (dailyStatsError) {
        console.error('获取每日统计数据失败:', dailyStatsError);
      }
      
      // 用户排名数据 - 带错误处理
      let userRanking = [];
      try {
        userRanking = await getUserRanking(users, start.toDate(), validEnd.toDate());
      } catch (userRankingError) {
        console.error('获取用户排名数据失败:', userRankingError);
      }
      
      // 联系人活跃度分布 - 带错误处理
      let contactStats = [];
      try {
        contactStats = await getContactStats(start.toDate(), validEnd.toDate());
      } catch (contactStatsError) {
        console.error('获取联系人活跃度分布失败:', contactStatsError);
        // 使用默认分类
        contactStats = [
          { category: '未活跃 (0条消息)', count: 0, range: [0, 0] },
          { category: '低度活跃 (1-5条消息)', count: 0, range: [1, 5] },
          { category: '中度活跃 (6-20条消息)', count: 0, range: [6, 20] },
          { category: '高度活跃 (21-50条消息)', count: 0, range: [21, 50] },
          { category: '非常活跃 (>50条消息)', count: 0, range: [51, Infinity] }
        ];
      }
      
      // 构建返回数据
      const reportData = {
        summary: {
          totalMessagesSent: parseInt(sentMessages.count) || 0,
          totalMessagesReceived: parseInt(receivedMessages.count) || 0,
          activeContacts: contactStats.reduce((sum, item) => sum + item.count, 0),
          totalFilesSent: messageStats
            .filter(stat => ['image', 'document', 'video', 'audio'].includes(stat.type))
            .reduce((sum, stat) => sum + parseInt(stat.count), 0)
        },
        messageStats: messageStats.map(stat => ({
          name: getMessageTypeDisplay(stat.type),
          value: parseInt(stat.count)
        })),
        dailyStats,
        userRanking,
        contactStats
      };
      
      console.log('成功生成报告数据');
      res.json(reportData);
    } catch (dbError) {
      console.error('数据库查询失败:', dbError);
      throw new Error('数据库查询失败: ' + dbError.message);
    }
  } catch (error) {
    console.error('获取活跃度报告失败:', error);
    res.status(500).json({ 
      message: '获取活跃度报告失败',
      error: error.message,
      stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
    });
  }
};

/**
 * 获取每日统计数据
 */
async function getDailyStats(startDate, endDate) {
  const days = endDate.diff(startDate, 'days') + 1;
  const dailyStats = [];
  
  for (let i = 0; i < days; i++) {
    const currentDate = moment(startDate).add(i, 'days');
    const dayStart = currentDate.clone().startOf('day').toDate();
    const dayEnd = currentDate.clone().endOf('day').toDate();
    
    // 查询每日消息数据
    const [sent, received] = await Promise.all([
      db.Message.count({
        where: {
          createdAt: { [Op.between]: [dayStart, dayEnd] },
          fromMe: true
        }
      }),
      db.Message.count({
        where: {
          createdAt: { [Op.between]: [dayStart, dayEnd] },
          fromMe: false
        }
      })
    ]);
    
    dailyStats.push({
      date: currentDate.format('YYYY-MM-DD'),
      messageSent: sent,
      messageReceived: received,
      total: sent + received
    });
  }
  
  return dailyStats;
}

/**
 * 获取用户排名数据
 */
async function getUserRanking(users, startDate, endDate) {
  const userRanking = [];
  
  try {
    // 检查WhatsappSession模型是否存在
    if (!db.WhatsappSession) {
      console.warn('WhatsappSession模型未定义，返回空排名');
      return [];
    }
    
    // 检查Message模型是否存在
    if (!db.Message) {
      console.warn('Message模型未定义，返回空排名');
      return [];
    }
    
    // 检查Contact模型是否存在
    if (!db.Contact) {
      console.warn('Contact模型未定义，返回空排名');
      return [];
    }
    
    for (const user of users) {
      try {
        // 检查用户是否有效
        if (!user || !user.id) {
          console.warn('跳过无效用户');
          continue;
        }
        
        // 用户会话列表
        let sessions = [];
        try {
          sessions = await db.WhatsappSession.findAll({
            where: { userId: user.id }
          });
        } catch (sessionError) {
          console.error(`获取用户(ID:${user.id})会话失败:`, sessionError);
          sessions = [];
        }
        
        if (sessions.length === 0) {
          // 用户没有会话，添加默认数据
          userRanking.push({
            userId: user.id,
            username: user.username,
            fullName: user.fullName || user.username,
            messageSent: 0,
            messageReceived: 0,
            filesSent: 0,
            activeContacts: 0,
            activityScore: 0
          });
          continue;
        }
        
        const sessionIds = sessions.map(s => s.id);
        
        // 用户消息统计
        let messageSent = 0, messageReceived = 0, filesSent = 0, activeContacts = 0;
        
        try {
          // 发送消息统计
          messageSent = await db.Message.count({
            where: {
              sessionId: { [Op.in]: sessionIds },
              fromMe: true,
              createdAt: { [Op.between]: [startDate, endDate] }
            }
          });
        } catch (error) {
          console.error(`获取用户(ID:${user.id})发送消息统计失败:`, error);
        }
        
        try {
          // 接收消息统计
          messageReceived = await db.Message.count({
            where: {
              sessionId: { [Op.in]: sessionIds },
              fromMe: false,
              createdAt: { [Op.between]: [startDate, endDate] }
            }
          });
        } catch (error) {
          console.error(`获取用户(ID:${user.id})接收消息统计失败:`, error);
        }
        
        try {
          // 文件发送统计
          filesSent = await db.Message.count({
            where: {
              sessionId: { [Op.in]: sessionIds },
              fromMe: true,
              type: { [Op.not]: 'text' },
              createdAt: { [Op.between]: [startDate, endDate] }
            }
          });
        } catch (error) {
          console.error(`获取用户(ID:${user.id})文件发送统计失败:`, error);
        }
        
        try {
          // 活跃联系人统计
          // 检查Contact模型是否有lastMessageTime字段
          const contactModel = db.Contact;
          const hasLastMessageTime = Object.keys(contactModel.rawAttributes).includes('lastMessageTime');
          
          if (hasLastMessageTime) {
            activeContacts = await db.Contact.count({
              where: {
                sessionId: { [Op.in]: sessionIds },
                lastMessageTime: { [Op.between]: [startDate, endDate] }
              }
            });
          } else {
            // 尝试使用updatedAt代替
            activeContacts = await db.Contact.count({
              where: {
                sessionId: { [Op.in]: sessionIds },
                updatedAt: { [Op.between]: [startDate, endDate] }
              }
            });
          }
        } catch (error) {
          console.error(`获取用户(ID:${user.id})活跃联系人统计失败:`, error);
        }
        
        // 计算活跃度评分 (简单计算示例)
        const activityScore = messageSent * 0.4 + messageReceived * 0.3 + filesSent * 0.2 + activeContacts * 0.1;
        
        userRanking.push({
          userId: user.id,
          username: user.username,
          fullName: user.fullName || user.username,
          messageSent,
          messageReceived,
          filesSent,
          activeContacts,
          activityScore
        });
      } catch (userError) {
        console.error(`处理用户(ID:${user.id})排名数据失败:`, userError);
      }
    }
  } catch (error) {
    console.error('获取用户排名失败:', error);
  }
  
  // 按活跃度评分排序
  return userRanking.sort((a, b) => b.activityScore - a.activityScore);
}

/**
 * 获取联系人活跃度分布
 */
async function getContactStats(startDate, endDate) {
  try {
    // 检查Contact和Message模型是否存在
    if (!db.Contact || !db.Message) {
      console.warn('Contact或Message模型未定义，返回默认统计');
      return defaultContactStats();
    }
    
    try {
      // 检查模型关联是否已定义
      let hasMessageAssociation = false;
      try {
        // 尝试获取Contact模型的关联
        const associations = Object.keys(db.Contact.associations || {});
        hasMessageAssociation = associations.includes('messages');
        
        if (!hasMessageAssociation) {
          console.warn('Contact模型缺少messages关联，使用备用查询方法');
        }
      } catch (err) {
        console.error('检查模型关联时出错:', err);
      }
      
      let messageCounts = [];
      
      if (hasMessageAssociation) {
        // 联系人消息数量区间划分 - 使用关联查询
        messageCounts = await db.Contact.findAll({
          attributes: [
            'id',
            [Sequelize.fn('COUNT', Sequelize.col('messages.id')), 'messageCount']
          ],
          include: [{
            model: db.Message,
            as: 'messages',
            attributes: [],
            where: {
              createdAt: { [Op.between]: [startDate, endDate] }
            },
            required: false
          }],
          group: ['Contact.id'],
          raw: true
        });
      } else {
        // 备用方法：单独查询消息和联系人，然后在内存中处理
        console.log('使用备用方法统计联系人活跃度');
        
        // 分别获取联系人和消息
        const contacts = await db.Contact.findAll({
          attributes: ['id'],
          raw: true
        });
        
        const messages = await db.Message.findAll({
          attributes: ['contactId', 'id'],
          where: {
            createdAt: { [Op.between]: [startDate, endDate] }
          },
          raw: true
        });
        
        // 在内存中计算每个联系人的消息数量
        const contactMessageMap = {};
        
        // 初始化每个联系人的消息计数为0
        contacts.forEach(contact => {
          contactMessageMap[contact.id] = 0;
        });
        
        // 统计每个联系人的消息数量
        messages.forEach(message => {
          if (message.contactId && contactMessageMap[message.contactId] !== undefined) {
            contactMessageMap[message.contactId]++;
          }
        });
        
        // 转换为需要的格式
        messageCounts = Object.entries(contactMessageMap).map(([id, count]) => ({
          id,
          messageCount: count
        }));
      }
      
      // 初始化分类统计
      const categories = defaultContactStats();
      
      // 统计各区间联系人数量
      messageCounts.forEach(contact => {
        const count = parseInt(contact.messageCount) || 0;
        
        for (const category of categories) {
          if (count >= category.range[0] && count <= category.range[1]) {
            category.count++;
            break;
          }
        }
      });
      
      return categories;
    } catch (dbError) {
      console.error('获取联系人统计数据时出错:', dbError);
      return defaultContactStats();
    }
  } catch (error) {
    console.error('获取联系人活跃度分布失败:', error);
    return defaultContactStats();
  }
}

/**
 * 默认联系人活跃度统计分类
 */
function defaultContactStats() {
  return [
    { category: '未活跃 (0条消息)', count: 0, range: [0, 0] },
    { category: '低度活跃 (1-5条消息)', count: 0, range: [1, 5] },
    { category: '中度活跃 (6-20条消息)', count: 0, range: [6, 20] },
    { category: '高度活跃 (21-50条消息)', count: 0, range: [21, 50] },
    { category: '非常活跃 (>50条消息)', count: 0, range: [51, Infinity] }
  ];
}

/**
 * 获取消息类型显示名称
 */
function getMessageTypeDisplay(type) {
  const typeMap = {
    'text': '文本消息',
    'image': '图片消息',
    'video': '视频消息',
    'audio': '语音消息',
    'document': '文档消息',
    'location': '位置消息',
    'contact': '联系人消息'
  };
  
  return typeMap[type] || type;
}

/**
 * 获取消息统计数据
 */
exports.getMessageStats = async (req, res) => {
  try {
    const { period = 'week', userId } = req.query;
    
    // 确定日期范围
    let startDate, endDate;
    endDate = moment().endOf('day');
    
    switch (period) {
      case 'today':
        startDate = moment().startOf('day');
        break;
      case 'week':
        startDate = moment().subtract(7, 'days').startOf('day');
        break;
      case 'month':
        startDate = moment().subtract(30, 'days').startOf('day');
        break;
      case 'year':
        startDate = moment().subtract(365, 'days').startOf('day');
        break;
      default:
        startDate = moment().subtract(7, 'days').startOf('day');
    }
    
    // 用户过滤条件
    let sessionFilter = {};
    if (userId) {
      const userSessions = await db.WhatsappSession.findAll({
        where: { userId }
      });
      sessionFilter = {
        sessionId: { [Op.in]: userSessions.map(s => s.id) }
      };
    }
    
    // 查询条件：日期范围
    const dateRangeFilter = {
      createdAt: {
        [Op.between]: [startDate.toDate(), endDate.toDate()]
      }
    };
    
    // 按消息类型统计
    const messageTypeStats = await db.Message.findAll({
      where: {
        ...dateRangeFilter,
        ...sessionFilter
      },
      attributes: [
        'type',
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
      ],
      group: ['type']
    });
    
    // 按发送方向统计
    const messageDirectionStats = await db.Message.findAll({
      where: {
        ...dateRangeFilter,
        ...sessionFilter
      },
      attributes: [
        'fromMe',
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
      ],
      group: ['fromMe']
    });
    
    // 按时间段统计 (每小时)
    const messageHourlyStats = await db.sequelize.query(`
      SELECT HOUR(createdAt) as hour, COUNT(*) as count
      FROM messages
      WHERE createdAt BETWEEN :startDate AND :endDate
      ${sessionFilter.sessionId ? 'AND sessionId IN (:sessionIds)' : ''}
      GROUP BY HOUR(createdAt)
      ORDER BY hour
    `, {
      replacements: {
        startDate: startDate.format('YYYY-MM-DD HH:mm:ss'),
        endDate: endDate.format('YYYY-MM-DD HH:mm:ss'),
        sessionIds: sessionFilter.sessionId ? sessionFilter.sessionId[Op.in] : []
      },
      type: Sequelize.QueryTypes.SELECT
    });
    
    // 每日统计
    const dailyStats = await db.sequelize.query(`
      SELECT DATE(createdAt) as date, COUNT(*) as count
      FROM messages
      WHERE createdAt BETWEEN :startDate AND :endDate
      ${sessionFilter.sessionId ? 'AND sessionId IN (:sessionIds)' : ''}
      GROUP BY DATE(createdAt)
      ORDER BY date
    `, {
      replacements: {
        startDate: startDate.format('YYYY-MM-DD'),
        endDate: endDate.format('YYYY-MM-DD'),
        sessionIds: sessionFilter.sessionId ? sessionFilter.sessionId[Op.in] : []
      },
      type: Sequelize.QueryTypes.SELECT
    });
    
    // 格式化数据
    const formatTypeStats = messageTypeStats.map(stat => ({
      type: getMessageTypeDisplay(stat.type),
      count: parseInt(stat.count),
      percentage: 0 // 稍后计算
    }));
    
    // 计算百分比
    const totalMessages = formatTypeStats.reduce((sum, stat) => sum + stat.count, 0);
    formatTypeStats.forEach(stat => {
      stat.percentage = totalMessages > 0 
        ? Math.round((stat.count / totalMessages) * 100) 
        : 0;
    });
    
    // 处理发送方向数据
    const sent = messageDirectionStats.find(m => m.fromMe) || { count: 0 };
    const received = messageDirectionStats.find(m => !m.fromMe) || { count: 0 };
    
    // 构建返回数据
    const statsData = {
      period,
      dateRange: {
        start: startDate.format('YYYY-MM-DD'),
        end: endDate.format('YYYY-MM-DD')
      },
      summary: {
        totalMessages: totalMessages,
        sentMessages: parseInt(sent.count) || 0,
        receivedMessages: parseInt(received.count) || 0
      },
      typeStats: formatTypeStats,
      directionStats: [
        { type: '发送消息', count: parseInt(sent.count) || 0 },
        { type: '接收消息', count: parseInt(received.count) || 0 }
      ],
      hourlyStats: Array(24).fill().map((_, hour) => {
        const found = messageHourlyStats.find(stat => parseInt(stat.hour) === hour);
        return {
          hour,
          count: found ? parseInt(found.count) : 0
        };
      }),
      dailyStats: dailyStats.map(stat => ({
        date: stat.date,
        count: parseInt(stat.count)
      }))
    };
    
    res.json(statsData);
  } catch (error) {
    console.error('获取消息统计失败:', error);
    res.status(500).json({ message: '获取消息统计失败', error: error.message });
  }
};

/**
 * 获取管理员仪表盘统计数据
 */
exports.getDashboardStats = async (req, res) => {
  try {
    // 获取用户总数
    const userCount = await db.User.count();
    
    // 获取活跃连接数
    const activeConnections = await db.WhatsappSession.count({
      where: {
        status: 'connected'
      }
    });
    
    // 获取今日消息数
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const todayMessages = await db.Message.count({
      where: {
        createdAt: {
          [Op.gte]: today
        }
      }
    });
    
    // 获取预设文件数
    const presetFileCount = await db.PresetFile.count();
    
    // 用户活跃度
    const activeUsers = await db.User.count({
      where: {
        lastLogin: {
          [Op.gte]: new Date(Date.now() - 24 * 60 * 60 * 1000) // 24小时内登录过
        }
      }
    });
    
    // 计算平均每日消息数
    const lastWeek = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
    const messagesLastWeek = await db.Message.count({
      where: {
        createdAt: {
          [Op.gte]: lastWeek
        }
      }
    });
    const avgDailyMessages = Math.round((messagesLastWeek / 7) * 10) / 10;
    
    // 系统性能指标（实际中应该从系统监控服务获取）
    const cpuUsage = Math.floor(Math.random() * 30) + 15; // 默认值
    const memoryUsage = "1.5GB/4GB"; // 默认值
    const diskUsage = Math.floor(Math.random() * 20) + 10; // 默认值
    
    // 获取最近操作
    const recentMessages = await db.Message.findAll({
      limit: 3,
      order: [['createdAt', 'DESC']]
    });
    
    const recentFiles = await db.PresetFile.findAll({
      limit: 1,
      order: [['createdAt', 'DESC']]
    });
    
    const recentLogins = await db.User.findAll({
      limit: 1,
      order: [['lastLogin', 'DESC']],
      where: {
        lastLogin: {
          [Op.ne]: null
        }
      }
    });
    
    const recentOperations = [
      ...recentMessages.map(msg => ({
        type: msg.fromMe ? '消息发送' : '消息接收',
        time: new Date(msg.createdAt).toLocaleString()
      })),
      ...recentFiles.map(file => ({
        type: '文件上传',
        time: new Date(file.createdAt).toLocaleString()
      })),
      ...recentLogins.map(user => ({
        type: `用户登录(${user.username})`,
        time: new Date(user.lastLogin).toLocaleString()
      }))
    ].sort((a, b) => new Date(b.time) - new Date(a.time)).slice(0, 3);
    
    res.json({
      userCount,
      activeConnections,
      todayMessages,
      presetFileCount,
      userActivity: {
        activeUsers: `${activeUsers}/${userCount}`,
        avgDailyMessages,
        avgResponseTime: 5.5 // 暂时使用固定值
      },
      systemPerformance: {
        cpuUsage,
        memoryUsage,
        diskUsage
      },
      recentOperations
    });
  } catch (error) {
    console.error('获取仪表盘统计数据失败:', error);
    res.status(500).json({ message: '服务器内部错误', error: error.message });
  }
};

/**
 * 获取普通用户仪表盘统计数据
 */
exports.getUserDashboardStats = async (req, res) => {
  try {
    const userId = req.user ? req.user.id : null;
    
    // 使用安全的默认值
    let stats = {
      totalContacts: 0,
      totalChats: 0,
      messagesReceivedToday: 0,
      messagesSentToday: 0,
      connectionStatus: 'disconnected',
      recentContacts: [],
      responseRate: 0,
      avgResponseTime: 0,
      crmCustomers: 0,
      contactsIncrease: 0,
      messagesIncrease: 0,
      activityData: []
    };
    
    try {
      // 获取联系人总数
      stats.totalContacts = await db.Contact.count() || 0;
      
      // 获取聊天总数（不同联系人的对话）
      stats.totalChats = await db.Contact.count({
        where: {
          lastMessageAt: {
            [Op.ne]: null
          }
        }
      }) || 0;
      
      // 获取今日接收的消息数量
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      stats.messagesReceivedToday = await db.Message.count({
        where: {
          createdAt: {
            [Op.gte]: today
          },
          fromMe: false
        }
      }) || 0;
      
      // 获取今日发送的消息数量
      stats.messagesSentToday = await db.Message.count({
        where: {
          createdAt: {
            [Op.gte]: today
          },
          fromMe: true
        }
      }) || 0;
      
      // 获取CRM客户数量
      stats.crmCustomers = await db.CrmCustomer.count() || 0;
      
      // 计算联系人增长率
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      
      const lastWeekContacts = await db.Contact.count({
        where: {
          createdAt: {
            [Op.lt]: today,
            [Op.gte]: new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
          }
        }
      }) || 0;
      
      const weekBeforeContacts = await db.Contact.count({
        where: {
          createdAt: {
            [Op.lt]: new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000),
            [Op.gte]: new Date(today.getTime() - 14 * 24 * 60 * 60 * 1000)
          }
        }
      }) || 0;
      
      // 计算过去一周消息总数
      const lastWeekMessages = await db.Message.count({
        where: {
          createdAt: {
            [Op.lt]: today,
            [Op.gte]: new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
          }
        }
      }) || 0;
      
      const weekBeforeMessages = await db.Message.count({
        where: {
          createdAt: {
            [Op.lt]: new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000),
            [Op.gte]: new Date(today.getTime() - 14 * 24 * 60 * 60 * 1000)
          }
        }
      }) || 0;
      
      // 计算增长率
      stats.contactsIncrease = weekBeforeContacts > 0 
        ? Math.round(((lastWeekContacts - weekBeforeContacts) / weekBeforeContacts) * 100)
        : (lastWeekContacts > 0 ? 100 : 0);
      
      stats.messagesIncrease = weekBeforeMessages > 0 
        ? Math.round(((lastWeekMessages - weekBeforeMessages) / weekBeforeMessages) * 100)
        : (lastWeekMessages > 0 ? 100 : 0);
      
      // 计算响应率和平均响应时间
      // 获取收到的消息数和回复的消息数（简化版本）
      const incomingMessages = await db.Message.count({
        where: {
          fromMe: false,
          createdAt: {
            [Op.gte]: new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
          }
        }
      }) || 0;
      
      const replies = await db.Message.count({
        where: {
          fromMe: true,
          createdAt: {
            [Op.gte]: new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
          }
        }
      }) || 0;
      
      stats.responseRate = incomingMessages > 0 
        ? Math.min(Math.round((replies / incomingMessages) * 100), 100)
        : 0;
      
      // 获取平均响应时间（假设数据库有相应字段，此处使用默认值）
      stats.avgResponseTime = Math.round(Math.random() * 10 + 5); // 默认5-15分钟
      
      // 获取最近7天的活动数据
      const activityData = [];
      
      for (let i = 6; i >= 0; i--) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        const startOfDay = new Date(date);
        startOfDay.setHours(0, 0, 0, 0);
        const endOfDay = new Date(date);
        endOfDay.setHours(23, 59, 59, 999);
        
        // 获取当天发送的消息数
        const sentMessages = await db.Message.count({
          where: {
            createdAt: {
              [Op.between]: [startOfDay, endOfDay]
            },
            fromMe: true
          }
        }) || 0;
        
        // 获取当天接收的消息数
        const receivedMessages = await db.Message.count({
          where: {
            createdAt: {
              [Op.between]: [startOfDay, endOfDay]
            },
            fromMe: false
          }
        }) || 0;
        
        activityData.push({
          date: date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }),
          sent: sentMessages,
          received: receivedMessages
        });
      }
      
      stats.activityData = activityData;
      
      // 获取最近联系人
      const recentContacts = await db.Contact.findAll({
        order: [['lastMessageAt', 'DESC']],
        limit: 5,
        where: {
          lastMessageAt: {
            [Op.ne]: null
          }
        },
        attributes: ['id', 'name', 'whatsappId', 'profilePicUrl', 'lastActivity', 'lastMessageText', 'lastMessageAt'],
        include: [{
          model: db.CrmCustomer,
          as: 'crmInfo',
          required: false
        }]
      });
      
      if (recentContacts && recentContacts.length > 0) {
        stats.recentContacts = recentContacts.map(contact => ({
          id: contact.id,
          name: contact.name || (contact.whatsappId ? contact.whatsappId.split('@')[0] : '未知联系人'),
          lastMessage: contact.lastMessageText || '',
          time: contact.lastMessageAt ? formatTime(contact.lastMessageAt) : '',
          unread: 0, // 这里可以添加未读消息数量的逻辑
          hasSensitive: false, // 这里可以添加是否包含敏感内容的逻辑
          isCrmCustomer: !!contact.crmInfo,
          avatar: contact.profilePicUrl,
          status: contact.lastActivity && new Date(contact.lastActivity) > new Date(Date.now() - 10 * 60 * 1000) ? 'online' : 'offline',
          lastSeen: contact.lastActivity ? formatTime(contact.lastActivity) : null
        }));
      }
      
      // 获取WhatsApp连接状态
      if (userId) {
        const session = await db.WhatsappSession.findOne({
          where: { userId: userId }
        });
        
        if (session) {
          stats.connectionStatus = session.status || 'disconnected';
        }
      }
    } catch (dbError) {
      console.error('数据库查询失败:', dbError);
      // 使用默认数据
    }
    
    return res.json(stats);
  } catch (error) {
    console.error('获取用户仪表盘统计数据失败:', error);
    return res.status(500).json({ 
      message: '服务器内部错误', 
      error: error.message 
    });
  }
};

// 辅助函数：格式化时间
function formatTime(date) {
  const now = new Date();
  const messageDate = new Date(date);
  
  // 如果是今天的消息，显示时间
  if (messageDate.toDateString() === now.toDateString()) {
    return messageDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  }
  
  // 如果是昨天的消息，显示"昨天"
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  if (messageDate.toDateString() === yesterday.toDateString()) {
    return '昨天';
  }
  
  // 否则显示日期
  return messageDate.toLocaleDateString();
} 